Page({
  data: {
    showMap: true,
    longitude: 116.39742,
    latitude: 24.29922, 
    markers: [],
    sites: [],
    textData: null,
    districts: [{ name: '全部', adcode: '441400', center: [116.3723, 24.29922] }],
    selectedDistrict: '441400',
    isLoading: false,
    scale: 10,
    allmask: true,
    isFirstLoad: true,
  },

  onLoad() {
    this.mapCtx = wx.createMapContext('map');
    this.fetchDistricts();
  },

  // 获取行政区划数据
  fetchDistricts() {
    const cacheKey = 'districts_cache';
    const cachedData = wx.getStorageSync(cacheKey);
    
    if (cachedData && Date.now() - cachedData.timestamp < 86400000) {
      console.log('使用缓存的行政区划数据');
      this.setData({ 
        districts: [...this.data.districts, ...cachedData.data]
      }, () => this.loadDataFromAMap());
      return;
    }
    
    console.log('从API获取行政区划数据');
    const url = 'https://restapi.amap.com/v3/config/district?key=48b0f6b31c4be2ebe4d531b187659fbd&keywords=梅州&subdistrict=1';

    wx.showLoading({ title: '加载行政区...' });
    wx.request({
      url,
      success: (res) => {
        if (res.data.status !== '1' || !res.data.districts?.[0]?.districts) {
          console.error('行政区划数据异常');
          wx.showToast({ title: '行政区数据异常', icon: 'none' });
          return;
        }

        console.log('成功获取行政区划数据，开始处理');
        const processed = this.processDistricts(res.data.districts[0].districts); 
        wx.setStorageSync(cacheKey, {
          data: processed, 
          timestamp: Date.now()
        }); 
        this.setData({ 
          districts: [...this.data.districts, ...processed]  
        }, () => this.loadDataFromAMap());
      },
      fail: (err) => {
        console.error('行政区划数据请求失败', err);
        wx.showToast({ title: '行政区加载失败', icon: 'none' });
      },
      complete: () => {
        wx.hideLoading();
        console.log('行政区划数据加载完成');
      }
    });
  },

  // 处理行政区数据
  processDistricts(districts) {
    console.log('开始处理行政区划数据');
    return districts
      .filter(d => !['市辖区'].includes(d.name))
      .map(d => ({
        name: d.name,
        adcode: d.adcode,
        center: d.center ? d.center.split(',').map(Number) : [116.3723, 24.29922],
        citycode: d.citycode
      }));
  },

  // 行政区切换
  onDistrictChange(e) {
    const adcode = e.currentTarget.dataset.adcode;
    if (!adcode || adcode === this.data.selectedDistrict) return;

    console.log('切换行政区划，adcode:', adcode);
    this.setData({ 
      selectedDistrict: adcode,
      markers: [],
      sites: [],
      textData: null 
    }, () => this.loadDataFromAMap());
  },

  // 加载地图数据
  async loadDataFromAMap() {
    if (this.data.isLoading) return;
    
    console.log('开始加载地图数据');
    this.setData({ isLoading: true });
    wx.showLoading({ title: '加载中...' });

    try {
      console.log('this.data.districts',this.data.districts);
      const currentDistrict = this.data.districts.find(d => d.adcode === this.data.selectedDistrict);
      console.log('currentDistrict',currentDistrict);
      // 优先从数据库读取
      const dbData = await this.fetchFromDatabase(currentDistrict.adcode);
      console.log('dbData',dbData);
      if (dbData.length > 0) {
        console.log('使用数据库中的POI数据');
        this.processMapData(dbData);
        this.processListData(dbData);
        this.adjustMapView(currentDistrict);
        return;
      }

      // 数据库无数据时请求API
      console.log('从API获取POI数据');
      const pois = await this.fetchPOIData(currentDistrict);
      if (pois.length === 0) return;

      // 处理地图数据+标记
      this.processMapData(pois);
      // 处理列表数据
      this.processListData(pois);
      //调整视图
      this.adjustMapView(currentDistrict);
    } catch (err) {
      console.error('地图数据加载失败', err);
      wx.showToast({ title: '数据加载失败', icon: 'none' });
    } finally {
      this.setData({ isLoading: false });
      wx.hideLoading();
      console.log('地图数据加载完成');
    }
  },

   // 新增数据库读取县区数据方法
   async fetchFromDatabase(adcode) {
    try {
      console.log('从数据库获取POI数据，adcode:', adcode);
      const { result } = await wx.cloud.callFunction({
        name: 'getPoiDataList',
        data: { adcode }
      });
  
      if (result.code === 200) {
        console.log('成功从数据库获取POI数据',result.data);
        return result.data; // 直接返回数据，无需转换 location
      }
      return [];
    } catch (err) {
      console.error('数据库查询失败', err);
      return [];
    }
  },
  // 从高德地图API获取POI数据
  // 修改后的从高德地图API获取POI数据方法
async fetchPOIData(district) {
  return new Promise(async (resolve, reject) => {
    console.log('开始从API获取POI数据');
    let allPois = [];
    let currentPage = 1;
    const pageSize = 50; // 每页最大数量
    let totalPages = 1;

    try {
      do {
        const pageData = await new Promise((pageResolve, pageReject) => {
          wx.request({
            url: 'https://restapi.amap.com/v3/place/text',
            data: {
              key: '48b0f6b31c4be2ebe4d531b187659fbd',
              keywords: '纪念馆',
              city: district.adcode,
              offset: pageSize,
              page: currentPage // 添加分页参数
            },
            success: (res) => {
              if (res.data.status !== '1') {
                console.error(`第${currentPage}页数据获取失败`, res.data.info);
                pageReject(new Error(res.data.info));
                return;
              }

              // 计算总页数（高德API返回的count可能有误差，需要动态判断）
              const totalCount = res.data.count || 0;
              totalPages = Math.ceil(totalCount / pageSize);
              
              // 合并数据
              allPois = [...allPois, ...(res.data.pois || [])];
              console.log(`已获取第${currentPage}页数据，累计${allPois.length}条`);

              pageResolve(true);
            },
            fail: (err) => {
              pageReject(err);
            }
          });
        });

        currentPage++;
        // 添加延时避免触发API频率限制（高德API一般限制50次/秒）
        await new Promise(resolve => setTimeout(resolve, 200));
      } while (currentPage <= totalPages);

      console.log('成功获取全部POI数据，总数：', allPois.length);
      
      // 存储到数据库
      try {
        console.log('开始存储POI数据到数据库');
        await wx.cloud.callFunction({
          name: 'savaPoiData',
          data: {
            pois: allPois.map(p => ({
              id: p.id,          // 必须字段
              name: p.name,      // 保留字段
              address: p.address,
              adname:p.adname,
              tel: p.tel,
              type: p.type,
              opentime2: (p.biz_ext && p.biz_ext.opentime2) || "",
              photos: p.photos || [],
              location:p.location,
              adcode: district.adcode,
              islike:false
            }))
          }
        });
        console.log('POI数据存储成功');
      } catch (err) {
        console.error('POI数据存储失败', err);
      }

      resolve(allPois);
    } catch (err) {
      console.error('POI数据获取失败', err);
      reject(err);
    }
  });
},

 

  

  // 处理地图数据+标记
processMapData(pois) {
  console.log('开始处理地图数据');
  // 过滤无效的location数据
  const validPois = pois.filter(item => item.location && item.location.includes(','));
  
  if (validPois.length > 0) {
    const firstLocation = validPois[0].location.split(',');
    this.setData({ 
      longitude: parseFloat(firstLocation[0]),
      latitude: parseFloat(firstLocation[1])
    });
  }
  console.log('找extra',validPois);
  const markers = validPois.map((item, index) => {
    const [longitude, latitude] = item.location.split(',').map(Number);
    return {
      id: index,
      latitude,
      longitude,
      title: item.name,
      iconPath: '../../images/img/marker.png',
      width: 32,
      height: 40,
      customCallout: { display: 'ALWAYS', content: item.name },
      extra: { id: item._id ? item._id : item.id }
    };
  });

  this.setData({ markers });
  console.log('地图标记数据处理完成');
},

  // 处理列表数据
  processListData(pois) {
    console.log('开始处理列表数据');
    const sites = pois.map(item => ({
      id: item._id ? item._id : item.id,
      title: item.name,
      address: item.address || '地址不详',
      tel: item.tel || '暂无电话',
      location: item.location,
      adname: item.adname,
      image: item.photos?.[0]?.url,
      tags: this.processTags(item.type)
    }));

    this.setData({ sites });
    console.log('列表数据处理完成');
  },

  // 处理标签
  processTags(typeString) {
    console.log('开始处理标签数据');
    try {
      return [...new Set(typeString.split(';').map(t => t.trim()).filter(Boolean))];
    } catch {
      console.error('标签处理失败');
      return ['未分类'];
    }
  },

  // 调整地图视野 
  adjustMapView(district) {
    console.log('调整地图视野');
    if (this.isFirstLoad) {  
      this.setData({
        isFirstLoad: false, 
        scale: 12
      });
    }
  },

  // 标记点击
  onMarkerTap(e) {
    console.log('地图标记被点击e',e);
    const markerId = e.markerId;
    const marker = this.data.markers.find(m => m.id === markerId);
    if (!marker) return;
    console.log(marker,'marker');
    console.log('sites',this.data.sites);
    const site = this.data.sites.find(s => s.id === marker.extra.id);
    console.log(site,'site');
    if (site) {
      this.setData({ textData: site });
      this.highlightMarker(markerId);
    }
  },

  // 高亮标记
  highlightMarker(markerId) {
    console.log('高亮地图标记markerId',markerId);
    const markers = this.data.markers.map(m => ({
      ...m,
      iconPath: m.id === markerId ? '../../images/img/marker_checked.png' : '../../images/img/marker.png'
    }));

    this.setData({ markers });
  },

  // 切换视图
  toggleView() {
    console.log('切换视图模式');
    const markers = this.data.markers.map(m => ({
      ...m,
      iconPath: '../../images/img/marker.png'
    }));

    this.setData({ 
      showMap: !this.data.showMap,
      textData: null,
      markers 
    });
  },

  // 查看详情
  goToDetail(e) {
    console.log('进入详情页面');
    const selectId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/mapInfo/mapInfo?id=' + selectId, 
    });
  }
});